﻿using Microsoft.AspNetCore.Components;

namespace MXERP.Infrastructure.Store
{
    public partial class TabState
    {
        public static class SetBody
        {
            public record Action(string Url, RouteData RouteData) : IAction;

            public class Handler : ActionHandler<Action>
            {
                public Handler(IStore store) : base(store) { }
                TabState TabState => Store.GetState<TabState>();
                RouteState RouteState => Store.GetState<RouteState>();

                public override Task Handle(Action action, CancellationToken cancellationToken)
                {
                    var tab = TabState.Tabs.Where(x => x.Url == action.Url).FirstOrDefault();
                    if (tab == null)
                    {
                        var route = RouteState.Routes?.Where(x => x.Path == action.Url).FirstOrDefault();
                        if (route == null)
                            return Task.CompletedTask;
                        tab = new Tab
                        {
                            Url = action.Url,
                            CreatedOn = DateTime.Now,
                            Title = route.Title,
                            Icon = route.Icon,
                            IsAffix = route.IsAffix,
                            IsKeepAlive = route.IsKeepAlive,
                            Body = CreateBody(action.RouteData)
                        };
                        TabState.Tabs.Add(tab);
                    }
                    tab.Body ??= CreateBody(action.RouteData);
                    return Task.CompletedTask;
                }
            }

            private static RenderFragment CreateBody(RouteData routeData)
            {
                return builder =>
                {
                    builder.OpenComponent(0, routeData.PageType);
                    foreach (var routeValue in routeData.RouteValues)
                    {
                        builder.AddAttribute(1, routeValue.Key, routeValue.Value);
                    }

                    //builder.AddComponentReferenceCapture(2, @ref =>
                    //{
                    //    GetPageInfo(item, item.Url, @ref);
                    //});

                    builder.CloseComponent();
                };
            }
        }
    }
}
